import { defineStore } from 'pinia'
import { ElNotification } from 'element-plus'
import {addMessage} from "@/api/system/message.js";


export const useWebSocket = defineStore('websocket', {
    state: () => ({
        socket: null,
        reconnectAttempts: 0,
        maxReconnectAttempts: 5,
        heartbeatInterval: null
    }),

    actions: {
        // 初始化WebSocket连接
        initWebSocket(userId) {
            if (this.socket) return

            const wsUrl = `ws://localhost:8080/websocket/${userId}`
            this.socket = new WebSocket(wsUrl)

            this.socket.onopen = () => {
                console.log('WebSocket连接成功')
                this.startHeartbeat()
                this.reconnectAttempts = 0
            }

            this.socket.onmessage = (event) => {
                try {
                    console.log('收到消息:', event.data)
                    const message = JSON.parse(event.data)
                    this.handleMessage(message)
                } catch (error) {
                    console.error('消息解析失败:', error)
                }
            }

            this.socket.onclose = (event) => {
                console.log('连接关闭:', event)
                this.clearHeartbeat()
                if (!event.wasClean) {
                    this.handleReconnect(userId)
                }
            }

            this.socket.onerror = (error) => {
                console.error('WebSocket错误:', error)
            }
        },

        // 消息处理
        handleMessage(message) {

            addMessage({
                userId:message.message.userId,
                readStatus:0,
                auditStatus:0,
                time:message.message.timestamp,
                content:message.message.content,
                title:message.message.title,
                orderId:message.message.orderId,
                changes:JSON.stringify(message.message.changes)
            })

            switch (message.message.type) {
                case 'notification':
                    ElNotification({
                        title: message.message.title,
                        message: message.message.content,
                        type: 'success',
                        duration: 5000
                    })
                    break
                case 'heartbeat':
                    console.log('收到心跳响应')
                    break
                default:
                    console.log('未知消息类型:', message.message)
                    console.log(message.type)
            }
        },

        // 心跳机制
        startHeartbeat() {
            this.heartbeatInterval = setInterval(() => {
                if (this.socket?.readyState === WebSocket.OPEN) {
                    this.socket.send(JSON.stringify({ type: 'heartbeat' }))
                }
            }, 30000)
        },

        clearHeartbeat() {
            if (this.heartbeatInterval) {
                clearInterval(this.heartbeatInterval)
                this.heartbeatInterval = null
            }
        },

        // 重连机制
        handleReconnect(userId) {
            if (this.reconnectAttempts < this.maxReconnectAttempts) {
                const delay = Math.min(1000 * 2 ** this.reconnectAttempts, 10000)
                console.log(`将在${delay}ms后尝试重连...`)

                setTimeout(() => {
                    this.reconnectAttempts++
                    this.initWebSocket(userId)
                }, delay)
            } else {
                console.error('达到最大重连次数，放弃连接')
            }
        },

        // 主动关闭连接
        closeWebSocket() {
            if (this.socket) {
                this.socket.close(1000, '正常关闭')
                this.socket = null
                this.clearHeartbeat()
            }
        },

        // 重新连接（用户切换时）
        reconnectWebSocket(newUserId) {
            this.closeWebSocket()
            this.initWebSocket(newUserId)
        }
    }
})
